package com.dongnao.network.nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Scanner;

/**
 * @author sjy
 * @date 2024年05月09日 18:11
 */
public class SocketChannelClient {

    public static void main(String[] args) throws Exception {
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        socketChannel.connect(new InetSocketAddress("127.0.0.1", 8080));
        //完成连接过程，如果channel是阻塞的，则 finishConnect 方法也是阻塞的，直到连接上或抛出异常
        //如果channel是非阻塞的，则 finishConnect 方法也是非阻塞的，连接上了返回true，否则返回 false
        while (!socketChannel.finishConnect()) {
            //没连接上，则一直等待
            Thread.yield();
        }

        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入：");
        //发送内容
        String msg = scanner.nextLine();
        ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
        while (buffer.hasRemaining()) {
            socketChannel.write(buffer);
        }
        //读取响应
        System.out.println("收到服务端响应：");
        ByteBuffer requestBuffer = ByteBuffer.allocate(1024);
        //socketChannel.read 是非阻塞的
        while (socketChannel.isOpen() && socketChannel.read(requestBuffer) != -1) {
            //长连接下，需要手动判断数据有没有读取结束(此处做一个简单的判断：超过0字节)
            if (requestBuffer.position() > 0) break;
            System.out.println("----空转----");
        }
        requestBuffer.flip();
        byte[] content = new byte[requestBuffer.limit()];
        requestBuffer.get(content);
        System.out.println(new String(content));
        scanner.close();
        socketChannel.close();
    }
}
